/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.system.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.system.bean.DistrictAndCorp;
import com.koron.system.domain.District;
import com.koron.system.domain.DistrictCorpRelation;
import com.koron.system.service.api.DistrictService;
import com.koron.system.utils.BusinessCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

@Api(tags = "district", description = "片区接口类")
@RestController
@RequestMapping("/district")
public class DistrictController {
    @Autowired
    private DistrictService districtService;


    @ApiOperation("保存片区和片区下的水司信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "details", value = "json字符串,格式为:{\"district\":{\"id\":\"\",\"code\":\"\",\"name\":\"xxx\",\"remark\":\"xxx\"},\"districtCorpRelationList\":[{\"corpCode\":\"xxx\"},{\"corpCode\":\"xxx\"}]}", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = true) final String details) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<Integer> msg = new MessageBean<>();
        if (StringUtils.isEmpty(details)) {
            msg.setCode(BusinessCode.DISTRICT_EMPTY_SAVE_DATA.getCode());
            msg.setDescription(BusinessCode.DISTRICT_EMPTY_SAVE_DATA.getDescription());
            return msg;
        }
        DistrictAndCorp districtAndCorp = new DistrictAndCorp();
        List<DistrictCorpRelation> relationList = new ArrayList<>();
        JSONObject jsonObject = JSON.parseObject(details);
        District district = new District();
        Date date = new Date();
       /* if (jsonObject != null && !jsonObject.isEmpty()) {
            jsonObject = jsonObject.getJSONObject("details");*/
        if (jsonObject != null && !jsonObject.isEmpty()) {
            JSONObject json = jsonObject.getJSONObject("district");
            if (json != null && !json.isEmpty()) {
                String id = json.getString("id");
                String name = json.getString("name");
                String code = json.getString("code");
                String remark = json.getString("remark");
                district.setId(id);
                district.setAddTime(date);
                district.setUpdateTime(date);
                district.setAddUser(user == null ? null : user.getName());
                district.setUpdateUser(user == null ? null : user.getName());
                district.setCode(code);
                district.setName(name);
                district.setRemark(remark);
            }
            JSONArray jsonArray = jsonObject.getJSONArray("districtCorpRelationList");
            if (jsonArray != null && !jsonArray.isEmpty()) {
                Iterator iterator = jsonArray.iterator();
                while (iterator.hasNext()) {
                    JSONObject js = (JSONObject) iterator.next();
                    String corpCode = js.getString("corpCode");
                    DistrictCorpRelation relation = new DistrictCorpRelation();
                    relation.setCorpCode(corpCode);
                    relation.setUpdateTime(date);
                    relation.setAddTime(date);
                    relation.setAddUser(user == null ? null : user.getName());
                    relation.setUpdateUser(user == null ? null : user.getName());
                    relationList.add(relation);
                }
            }
        }
        //}
        districtAndCorp.setDistrict(district);
        districtAndCorp.setDistrictCorpRelationList(relationList);
        msg = districtService.save(districtAndCorp);
        return msg;
    }


    @ApiOperation("根据主键获取片区信息详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "片区id:", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/districtDetails.htm", method = RequestMethod.POST)
    public MessageBean<District> districtDetails(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String id) {
        if (null == user) {
            MessageBean<District> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<District> msg = districtService.queryOne(id);
        return msg;
    }


    @ApiOperation("根据主键删除片区信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "片区id:", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/deleteDistrict.htm", method = RequestMethod.POST)
    public MessageBean<Integer> deleteDistrict(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        return districtService.deleteDistrict(id);
    }


    @ApiOperation("根据主键删除片区与水司之间的关联")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "片区与水司之间的关联id,多个之间用，分开", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/deleteDistrictCorp.htm", method = RequestMethod.POST)
    public MessageBean<Integer> deleteDistrictCorp(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String ids) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        String[] idArray = ids.split("[,，]");
        return districtService.deleteDistrictCorp(Arrays.asList(idArray));
    }


    @ApiOperation("获取片区列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页" , dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数" , dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/districtList.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<District>> districtList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, Integer page, Integer pageSize) {
        if (null == user) {
            MessageBean<DataBean<District>> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean<District>> msg = districtService.queryAllDistrict(start, pageSize);
        msg.getData().setPageNo((page == null || page == 0) ? 1 : page);
        msg.getData().setPageSize((pageSize == null || pageSize == 0) ? 10 : pageSize);
        return msg;
    }


    @ApiOperation("根据片区code获取该片区关联的水司")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "districtCode", value = "片区code", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/queryDistrictCorp.htm", method = RequestMethod.POST)
    public MessageBean<List<DistrictCorpRelation>> queryDistrictCorp(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String districtCode) {
        if (null == user) {
            MessageBean<List<DistrictCorpRelation>> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        MessageBean<List<DistrictCorpRelation>> msg = new MessageBean<>();
        msg.setCode(BusinessCode.SUCCESS.getCode());
        msg.setDescription(BusinessCode.SUCCESS.getDescription());
        msg.setData(districtService.queryAssociatedCorp(districtCode));
        return msg;
    }

}
